package com.css.ids.server.task;

import java.util.concurrent.Callable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.css.ids.server.common.Constants;
import com.css.ids.server.observer.ClientInfo;
import com.css.util.StringHelper;

public final class SendDataToClientTask implements Callable<String> {
	private static final Log _logger = LogFactory.getLog(SendDataToClientTask.class);
	
		private byte[] data;
		private ClientInfo client;
		private int sendedCount = 1;
		public SendDataToClientTask(byte[] data, ClientInfo client) {
			this.data = data;
			this.client = client;
		}
		public SendDataToClientTask(byte[] data, ClientInfo client, int sendedCount) {
			this.data = data;
			this.client = client;
			this.sendedCount = sendedCount;
		}
		@Override
		public String call() throws Exception {
			String msg = "";
			if(this.sendedCount>Constants.sendCount){
				msg = client.getName()+"`s sendedCount over "+Constants.sendCount+".";
				_logger.error(msg);
				return msg;
			}
			String syncUrl = client.getSyncUrl();
			if(StringHelper.isEmpty(syncUrl)){
				msg = client.getName()+"`s syncUrl["+syncUrl+"] is empty.";
				_logger.error(msg);
				return msg;
			}
			if(syncUrl.indexOf("?")==-1 || syncUrl.endsWith("?")){
				msg = client.getName()+"`s syncUrl["+syncUrl+"] donot have operation.";
				_logger.error(msg);
				return msg;
			}
			int index = syncUrl.indexOf("?");
			try {
				AXIS2Sender<String> sender = new AXIS2Sender<String>(syncUrl.substring(0,index), syncUrl.substring(index+1));
				String result = sender.send(data);
				if("error".equals(result)){
					throw new Exception(result);
				}
			} catch (Exception e) {
				if(this.sendedCount<Constants.sendCount){
					this.sendedCount++;
					new PushTaskToThreadPoolThread(this).run();
				}
				msg = client.getName()+"`s syncUrl["+syncUrl+"] cannot be used." + "\n" + e.getMessage();
				_logger.error(msg);
				return msg;
			}
			return "success";
		}
		
	}